package com.hgy.fxui.controller;

import com.hgy.fxui.dao.DrugDao;
import com.hgy.fxui.dao.PurchaseOrderDao;
import com.hgy.fxui.dao.SupplierDao;
import com.hgy.fxui.model.Drug;
import com.hgy.fxui.model.PurchaseOrder;
import com.hgy.fxui.model.Supplier;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Controller
public class PurchaseManagementController {

    @Setter private PurchaseOrderDao purchaseOrderDao;
    @Setter private SupplierDao supplierDao;
    @Setter private DrugDao drugDao;

    @FXML private TableView<PurchaseOrder> purchaseTable;
    @FXML private TableColumn<PurchaseOrder, Integer> idColumn;
    @FXML private TableColumn<PurchaseOrder, String> operationTimeColumn;
    @FXML private TableColumn<PurchaseOrder, String> supplierColumn;
    @FXML private TableColumn<PurchaseOrder, String> drugColumn;
    @FXML private TableColumn<PurchaseOrder, String> specColumn;
    @FXML private TableColumn<PurchaseOrder, String> typeColumn;
    @FXML private TableColumn<PurchaseOrder, Integer> quantityColumn;
    @FXML private TableColumn<PurchaseOrder, Double> unitPriceColumn;
    @FXML private TableColumn<PurchaseOrder, Double> totalPriceColumn;
    @FXML private TableColumn<PurchaseOrder, String> operatorColumn;
    @FXML private TableColumn<PurchaseOrder, String> noteColumn;

    @FXML private RadioButton purchaseRadio;
    @FXML private RadioButton returnRadio;
    @FXML private ComboBox<Supplier> supplierCombo;
    @FXML private ComboBox<Drug> drugCombo;
    @FXML private Label stockLabel;
    @FXML private TextField quantityField;
    @FXML private TextField priceField;
    @FXML private TextField noteField;

    // 添加ToggleGroup
    private final ToggleGroup operationType = new ToggleGroup();

    private final ObservableList<PurchaseOrder> purchaseList = FXCollections.observableArrayList();
    private final ObservableList<Supplier> supplierList = FXCollections.observableArrayList();
    private final ObservableList<Drug> drugList = FXCollections.observableArrayList();

    private boolean isUISetupCompleted = false;

    @FXML
    public void initialize() {
        log.info("采购管理初始化开始...");

        // 初始化ToggleGroup
        purchaseRadio.setToggleGroup(operationType);
        returnRadio.setToggleGroup(operationType);
        purchaseRadio.setSelected(true);

        if (!isUISetupCompleted) {
            basicUIInitialize();
            isUISetupCompleted = true;
        }

        log.info("采购管理初始化完成...");
    }

    public void fullInitialize() {
        log.info("开始完整初始化采购管理...");

        if (purchaseOrderDao == null || supplierDao == null || drugDao == null) {
            throw new IllegalStateException("DAO未初始化!");
        }

        if (!isUISetupCompleted) {
            basicUIInitialize();
            isUISetupCompleted = true;
        }

        purchaseTable.setSelectionModel(null);

        // 加载采购记录
        loadPurchaseData();

        // 加载供应商数据
        loadSuppliers();

        // 加载药品数据
        loadDrugs();

        // 设置供应商组合框回调
        supplierCombo.setCellFactory(new Callback<ListView<Supplier>, ListCell<Supplier>>() {
            @Override
            public ListCell<Supplier> call(ListView<Supplier> param) {
                return new ListCell<>() {
                    @Override
                    protected void updateItem(Supplier item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item == null || empty) {
                            setText(null);
                        } else {
                            setText(item.getName() + " - " + item.getContactPerson());
                        }
                    }
                };
            }
        });

        supplierCombo.setButtonCell(new ListCell<>() {
            @Override
            protected void updateItem(Supplier item, boolean empty) {
                super.updateItem(item, empty);
                if (item == null || empty) {
                    setText(null);
                } else {
                    setText(item.getName());
                }
            }
        });

        // 设置药品组合框回调
        drugCombo.setCellFactory(new Callback<ListView<Drug>, ListCell<Drug>>() {
            @Override
            public ListCell<Drug> call(ListView<Drug> param) {
                return new ListCell<>() {
                    @Override
                    protected void updateItem(Drug item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item == null || empty) {
                            setText(null);
                        } else {
                            setText(item.getName() + " (" + item.getSpecification() + ")");
                        }
                    }
                };
            }
        });

        drugCombo.setButtonCell(new ListCell<>() {
            @Override
            protected void updateItem(Drug item, boolean empty) {
                super.updateItem(item, empty);
                if (item == null || empty) {
                    setText(null);
                } else {
                    setText(item.getName());
                }
            }
        });

        // 药品选择事件监听
        drugCombo.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                stockLabel.setText(String.valueOf(newValue.getStock()));
                priceField.setText(String.valueOf(newValue.getPrice()));
            } else {
                stockLabel.setText("");
                priceField.setText("");
            }
        });

        log.info("采购管理完整初始化完成");
    }

    private void basicUIInitialize() {
        log.debug("执行基础UI初始化...");

        // 初始化表格列
        idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));

        // 格式化操作时间
        operationTimeColumn.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getOperationTime()
                        .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))));

        supplierColumn.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getSupplierName()));

        drugColumn.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getDrugName()));

        specColumn.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getDrugSpec()));

        typeColumn.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getOrderType()));

        quantityColumn.setCellValueFactory(new PropertyValueFactory<>("quantity"));
        unitPriceColumn.setCellValueFactory(new PropertyValueFactory<>("unitPrice"));
        totalPriceColumn.setCellValueFactory(new PropertyValueFactory<>("totalPrice"));
        operatorColumn.setCellValueFactory(new PropertyValueFactory<>("operator"));
        noteColumn.setCellValueFactory(new PropertyValueFactory<>("note"));

        // 设置数量列特殊显示（正数为绿色，负数为红色）
        quantityColumn.setCellFactory(column -> new TableCell<>() {
            @Override
            protected void updateItem(Integer item, boolean empty) {
                super.updateItem(item, empty);
                if (item == null || empty) {
                    setText(null);
                    setStyle("");
                } else {
                    setText(String.valueOf(Math.abs(item)));
                    if (item > 0) {
                        setStyle("-fx-text-fill: green; -fx-font-weight: bold;");
                    } else {
                        setStyle("-fx-text-fill: red; -fx-font-weight: bold;");
                    }
                }
            }
        });

        // 设置类型列特殊显示（采购为绿色，退货为红色）
        typeColumn.setCellFactory(column -> new TableCell<>() {
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (item == null || empty) {
                    setText(null);
                    setStyle("");
                } else {
                    if ("PURCHASE".equals(item)) {
                        setText("进货");
                        setStyle("-fx-text-fill: green; -fx-font-weight: bold;");
                    } else if ("RETURN".equals(item)) {
                        setText("退货");
                        setStyle("-fx-text-fill: red; -fx-font-weight: bold;");
                    } else {
                        setText(item);
                        setStyle("");
                    }
                }
            }
        });

        // 设置总价列保留两位小数
        totalPriceColumn.setCellFactory(column -> new TableCell<>() {
            @Override
            protected void updateItem(Double item, boolean empty) {
                super.updateItem(item, empty);
                if (item == null || empty) {
                    setText(null);
                } else {
                    setText(String.format("%.2f", item));
                }
            }
        });

        purchaseTable.setItems(purchaseList);

        log.debug("基础UI初始化完成");
    }

    private void loadPurchaseData() {
        if (purchaseOrderDao == null) {
            log.error("尝试加载数据时purchaseOrderDao为null!");
            return;
        }

        try {
            log.info("开始从数据库加载采购记录数据...");
            List<PurchaseOrder> orders = purchaseOrderDao.getAllPurchaseOrders();

            if (orders == null) {
                log.warn("purchaseOrderDao.getAllPurchaseOrders()返回null");
            } else {
                log.info("成功加载 {} 条采购记录", orders.size());
                purchaseList.setAll(orders);
            }
        } catch (Exception e) {
            log.error("加载采购记录数据失败", e);
            showAlert("无法加载采购记录数据: " + e.getMessage());
        }
    }

    private void loadSuppliers() {
        if (supplierDao == null) {
            log.error("尝试加载数据时supplierDao为null!");
            return;
        }

        try {
            log.info("开始从数据库加载供应商数据...");
            List<Supplier> suppliers = supplierDao.getAllSuppliers();

            if (suppliers == null) {
                log.warn("supplierDao.getAllSuppliers()返回null");
            } else {
                log.info("成功加载 {} 条供应商数据", suppliers.size());
                supplierList.setAll(suppliers);
                supplierCombo.setItems(supplierList);
            }
        } catch (Exception e) {
            log.error("加载供应商数据失败", e);
            showAlert("无法加载供应商数据: " + e.getMessage());
        }
    }

    private void loadDrugs() {
        if (drugDao == null) {
            log.error("尝试加载数据时drugDao为null!");
            return;
        }

        try {
            log.info("开始从数据库加载药品数据...");
            List<Drug> drugs = drugDao.getAllDrugs();

            if (drugs == null) {
                log.warn("drugDao.getAllDrugs()返回null");
            } else {
                log.info("成功加载 {} 条药品数据", drugs.size());
                drugList.setAll(drugs);
                drugCombo.setItems(drugList);
            }
        } catch (Exception e) {
            log.error("加载药品数据失败", e);
            showAlert("无法加载药品数据: " + e.getMessage());
        }
    }

    @FXML
    private void handleRefresh() {
        log.info("用户点击刷新数据");
        loadPurchaseData();
    }

    @FXML
    private void handleResetForm() {
        log.info("用户重置表单");
        supplierCombo.getSelectionModel().clearSelection();
        drugCombo.getSelectionModel().clearSelection();
        quantityField.clear();
        priceField.clear();
        noteField.clear();
        stockLabel.setText("");
        purchaseRadio.setSelected(true);
    }

    @FXML
    private void handleConfirmOperation() {
        log.info("用户确认采购/退货操作");

        // 表单验证
        if (!validateForm()) {
            return;
        }

        Supplier selectedSupplier = supplierCombo.getValue();
        Drug selectedDrug = drugCombo.getValue();
        String operationTypeStr = purchaseRadio.isSelected() ? "PURCHASE" : "RETURN";
        int quantity = purchaseRadio.isSelected()
                ? Integer.parseInt(quantityField.getText())
                : -Integer.parseInt(quantityField.getText());
        double unitPrice = Double.parseDouble(priceField.getText());
        String note = noteField.getText();

        // 退货操作验证库存
        if (operationTypeStr.equals("RETURN")) {
            int returnQuantity = Integer.parseInt(quantityField.getText());
            if (returnQuantity > selectedDrug.getStock()) {
                showAlert("退货数量不能超过当前库存量!");
                return;
            }
        }

        // 创建采购记录对象
        PurchaseOrder order = PurchaseOrder.builder()
                .supplierId(selectedSupplier.getId())
                .supplierName(selectedSupplier.getName())
                .drugId(selectedDrug.getId())
                .drugName(selectedDrug.getName())
                .drugSpec(selectedDrug.getSpecification())
                .orderType(operationTypeStr)
                .quantity(quantity)
                .unitPrice(unitPrice)
                .totalPrice(quantity * unitPrice)
                .operator("admin") // TODO: 替换为实际操作员
                .operationTime(LocalDate.now())
                .note(note)
                .build();

        try {
            // 保存采购记录
            int rows = purchaseOrderDao.insert(order);
            if (rows > 0) {
                log.info("采购/退货操作成功: {}", order);

                // 更新药品库存
                if (operationTypeStr.equals("PURCHASE")) {
                    selectedDrug.setStock(selectedDrug.getStock() + Math.abs(quantity));
                } else {
                    selectedDrug.setStock(selectedDrug.getStock() - Math.abs(quantity));
                }
                drugDao.update(selectedDrug);

                // 刷新数据
                loadPurchaseData();

                // 重置表单
                handleResetForm();

                showSuccessAlert();
            } else {
                log.warn("数据库插入操作未成功");
                showAlert("操作失败，请重试");
            }
        } catch (Exception e) {
            log.error("保存采购记录失败", e);
            showAlert("操作失败: " + e.getMessage());
        }
    }

    private boolean validateForm() {
        StringBuilder errorMessage = new StringBuilder();

        if (supplierCombo.getValue() == null) {
            errorMessage.append("请选择供应商!\n");
        }

        if (drugCombo.getValue() == null) {
            errorMessage.append("请选择药品!\n");
        }

        String quantityText = quantityField.getText().trim();
        if (quantityText.isEmpty()) {
            errorMessage.append("请输入数量!\n");
        } else {
            try {
                int qty = Integer.parseInt(quantityText);
                if (qty <= 0) {
                    errorMessage.append("数量必须大于0!\n");
                }

                // 退货操作额外验证
                if (returnRadio.isSelected()) {
                    Drug drug = drugCombo.getValue();
                    if (drug != null && qty > drug.getStock()) {
                        errorMessage.append("退货数量不能超过当前库存(" + drug.getStock() + ")!\n");
                    }
                }
            } catch (NumberFormatException e) {
                errorMessage.append("数量必须是整数!\n");
            }
        }

        String priceText = priceField.getText().trim();
        if (priceText.isEmpty()) {
            errorMessage.append("请输入单价!\n");
        } else {
            try {
                double price = Double.parseDouble(priceText);
                if (price <= 0) {
                    errorMessage.append("单价必须大于0!\n");
                }
            } catch (NumberFormatException e) {
                errorMessage.append("单价必须是数字!\n");
            }
        }

        if (!errorMessage.isEmpty()) {
            showAlert(errorMessage.toString());
            return false;
        }

        return true;
    }

    private void showAlert(String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    private void showSuccessAlert() {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("成功");
        alert.setHeaderText(null);
        alert.setContentText("操作成功!");
        alert.showAndWait();
    }
}